package utils;

import exceptions.ConfigException;
import vo.Config;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Path;
import java.util.List;
import java.util.Properties;
import java.util.prefs.BackingStoreException;
import java.util.prefs.Preferences;

/**
 * @author Timur Yarosh
 *         Date: 02.06.13
 *         Time: 13:21
 */
public class ConfigUtils {
    /**
     * @deprecated
     * Check if all configs exists'
     * @param configs config paths to check
     * @return false if one or all configs are not exists
     */
    public static boolean checkConfigs(List<Path> configs) {
        boolean exists = false;
        for (Path config : configs) {
            exists = config.toFile().exists();
            if (!exists) {
                break;
            }
        }
        return exists;
    }

    /**
     * Check if all configs exists'
     * @param configs config paths to check
     * @return false if one or all configs are not exists
     */
    public static boolean checkConfigs(String[] configs) throws BackingStoreException {
        boolean exists = true;
        for (String config : configs) {
            exists = Preferences.userRoot().nodeExists(config);
            if (!exists) {
                break;
            }
        }
        return exists;
    }

    public static void storeConfig(Config config) throws IOException {
//        config.getProps().store(config.getWriter(), null);
        Preferences preferences = Preferences.userRoot().node(config.getPath());
        for (Object key : config.getProps().keySet()) {
            preferences.put(key.toString(), config.getProps().getProperty(key.toString()));
        }
    }

    public static Config loadConfig(String pathName) throws BackingStoreException {
        Preferences preferences = Preferences.userRoot().node(pathName);
        Properties properties = new Properties();
        for (String key : preferences.keys()) {
            properties.setProperty(key, preferences.get(key, null));
        }
        return new Config(properties, pathName);
    }

    public static Config loadConfig(InputStream inputStream, String path) throws IOException {
        Properties properties = new Properties();
        properties.load(inputStream);
        return new Config(properties, path);
    }

    public static Config loadIniConfig(String path, String storingPath) throws IOException, ConfigException {
        return ConfigurationReader.loadConfig(path, storingPath);
    }

    public static String[] listConfigs() throws BackingStoreException {
        return Preferences.userRoot().keys();
    }

}
